package com.hhf.riceshopping.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 解决feign远程调用丢失请求头的问题
 */
@Configuration
public class RiceFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        //也就是说feign在远程调用之前都先经过每一个拦截器的apply
       return new RequestInterceptor() {

           /**
            * @param template 新请求
            */
           @Override
           public void apply(RequestTemplate template) {
               //整个上下文环境的保持器,getRequestAttributes可以拿到当前的整个请求属性
               ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
               if (attributes != null) {
                   HttpServletRequest request = attributes.getRequest();  //老请求
                   if (request != null) {
                       //同步请求头数据，主要同步cookie
                       String cookie = request.getHeader("Cookie");
                       //给新请求同步了老请求的cookie信息
                       template.header("Cookie", cookie);
                   }
               }
           }
       };
    }
}
